/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2020-02-17
*/
package com.rzico.basics.controller.admin;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rzico.annotation.Log;
import com.rzico.base.BaseController;
import com.rzico.base.CommResult;
import com.rzico.basics.entity.Enterprise;
import com.rzico.basics.entity.Supplier;
import com.rzico.basics.service.EnterpriseService;
import com.rzico.basics.service.SupplierService;
import com.rzico.core.entity.SysMch;
import com.rzico.core.entity.SysMchMenu;
import com.rzico.core.entity.SysUser;
import com.rzico.core.service.SysUserService;
import com.rzico.entity.PageResult;
import com.rzico.entity.Pageable;
import com.rzico.exception.CustomException;
import com.rzico.util.MD5Utils;
import com.rzico.util.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 供应商控制层
 *
 * @author Rzico Boot
 * @version 1.0
 * @date 2020-02-17
 */
@Api(description = "供应商接口")
@RestController
@RequestMapping("/admin/supplier")
public class SupplierAdminController extends BaseController {

    @Autowired
    private SupplierService supplierService;

    @Autowired
    private EnterpriseService enterpriseService;

    @Autowired
    private SysUserService sysUserService;

    /**
     * 分页查询供应商
     *
     * @return
    */
    @ApiOperation("分页查询供应商")
    @GetMapping("/list")
    @ApiImplicitParams({@ApiImplicitParam(name = "startDate", value = "开始时间", dataType = "String", paramType = "query") ,
            @ApiImplicitParam(name = "endDate", value = "结束时间", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "supplierCategoryId", value = "供应商分类", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "供应商名称", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "address", value = "地址", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "phone", value = "联系电话", dataType = "String", paramType = "query")
    })
    public CommResult<Supplier> list(String startDate, String endDate,Boolean deleted,Long supplierCategoryId,String name,String address,String phone, Pageable pageable) {
        Map<String, Object> params = new HashMap<String, Object>();
        params = buildSortField(params, pageable);
        if (StringUtils.isNotEmpty(startDate)){
            params.put("startDate", startDate);
        }
        if (StringUtils.isNotEmpty(endDate)){
            params.put("endDate", endDate);
        }

        Enterprise enterprise = enterpriseService.getCurrent();
        if (enterprise!=null) {
            params.put("enterpriseId", enterprise.getId());
        } else {
            return CommResult.error("没有开通企业");
        }

        //非管理员都启用数据权限
        SysUser sysUser = sysUserService.getCurrent();
//        if (!sysUserService.isAdmin(sysUser)) {
//            params.put("dataScopeId",sysUser.getId());
//        }

        if (StringUtils.isNotEmpty(name)) {
            params.put("name",name);
        }

        if (StringUtils.isNotEmpty(address)) {
            params.put("address",address);
        }

        if (supplierCategoryId!=null) {
            if (supplierCategoryId==0L) {
                params.put("supplierCategoryId", supplierCategoryId);
            } else {
                params.put("treePath", String.valueOf(supplierCategoryId));
            }
        }

        if (StringUtils.isNotEmpty(phone)) {
            params.put("phone",phone);
        }
        if (deleted!=null) {
            params.put("deleted",deleted);
        } else {
            params.put("deleted", false);
        }


        //检查是否供应商账号
        Supplier supplier = supplierService.findByUserId(sysUser.getId());
        if (supplier!=null) {
            params.put("id",supplier.getId());
        }


        Page<Object> startPage = PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
        List<Supplier> list = supplierService.selectList(params);
        PageResult<Supplier> pageResult = new PageResult<Supplier>(list, startPage.getTotal(), pageable);
        return CommResult.success(pageResult);
    }

    /**
     * 查询单条供应商
     *
     * @return
    */
    @ApiOperation("查询单条供应商")
    @GetMapping("/find/{id}")
    public CommResult<Supplier> find(@PathVariable String id) {
        Supplier result = supplierService.findById(id);

        Map<String,Object> data = new HashMap<>();
        data.put("supplier",result);
        return CommResult.success(result);

    }

    /**
     * 保存供应商
     *
     * @param supplier
     * @return
     */
    @ApiOperation("保存供应商")
    @PostMapping("/save")
    @ApiImplicitParams({@ApiImplicitParam(name = "password", value = "登录密码 MD5后传入", dataType = "String", paramType = "query")
    })
    public CommResult<Supplier> save(@RequestBody Supplier supplier,String password) {
        Assert.notNull(supplier.getName(), "名称为空");
        Enterprise enterprise = enterpriseService.getCurrent();
        if (enterprise!=null) {
            supplier.setEnterpriseId(enterprise.getId());
        } else {
            return CommResult.error("没有开通企业");
        }
        supplier.setDeleted(false);
        if (null == supplier.getTax()){
            supplier.setTax(new BigDecimal(0.17));
        }
        supplier.setCreateDate(new Date());
        if (supplier.getUsername()!=null && !"".equals(supplier.getUsername())) {
            if (sysUserService.checkUserExists(supplier.getUsername())>0) {
                throw new CustomException("用户名已经存在");
            }
        }
        supplier = supplierService.save(supplier,password);
        Supplier result = supplierService.findById(supplier.getId());
        return CommResult.success(result);

    }


    /**
     * 批量删除供应商
     *
     * @param ids
     * @return
     */
    @Log(desc = "批量删除供应商", type = Log.LOG_TYPE.DEL)
    @ApiOperation("批量删除供应商,ids用逗号拼接")
    @PostMapping("/del/{ids}")
    public CommResult<Supplier> del(@PathVariable String ids) {

        supplierService.deleteByIds(ids.split(","));
        return CommResult.success();
    }

    /**
     * 更新供应商
     *
     * @param supplier
     * @return
     */
    @Log(desc = "更新供应商", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation("更新供应商")
    @PostMapping("/update")
    public CommResult<Supplier> update(@RequestBody Supplier supplier) {
        supplier.setUserId(null);
        supplier.setUsername(null);
        int affectCount = supplierService.updateByPrimaryKeySelective(supplier);
        if (affectCount <= 0){
            return CommResult.error();
        }
        Supplier result = supplierService.findById(supplier.getId());
        return CommResult.success(result);
    }

    /**
     * 重置密码
     *
     * @param id
     * @return
     */
    @ApiOperation("重置密码")
    @PostMapping("/resetPwd")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "供应商ID", dataType = "String", allowMultiple = true, paramType = "query")})
    public CommResult<SysMchMenu> resetPwd(String id) {
        Assert.notNull(id, "供应商ID为空");

        Supplier supplier = supplierService.findById(id);

        if (supplier.getUserId()==null) {
            return CommResult.error("没有绑定用户");
        }

        SysUser sysUser = sysUserService.findById(supplier.getUserId());
        if (sysUser==null) {
            return CommResult.error("没找到用户");
        }

        String password = MD5Utils.getMD5Str(sysUser.getUsername());
        sysUser.setPassword(MD5Utils.getMD5Str(password.trim() + sysUser.getUsername().trim()));

        sysUserService.updateByPrimaryKeySelective(sysUser);

        return CommResult.success();

    }

}
